package com.stellar.auth.domain.authRole.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.stellar.auth.basic.entity.AuthPermission;
import com.stellar.auth.basic.entity.AuthRole;
import com.stellar.auth.basic.entity.AuthRolePermission;
import com.stellar.auth.basic.entity.AuthUserRole;
import com.stellar.auth.basic.service.AuthPermissionService;
import com.stellar.auth.basic.service.AuthRolePermissionService;
import com.stellar.auth.basic.service.AuthRoleService;
import com.stellar.auth.basic.service.AuthUserRoleService;
import com.stellar.auth.constants.ErrorCodeConstants;
import com.stellar.auth.controller.admin.authPermission.vo.AuthPermissionResponseVO;
import com.stellar.auth.controller.admin.authRole.vo.AuthRoleRequestPageVO;
import com.stellar.auth.controller.admin.authRole.vo.AuthRoleRequestVO;
import com.stellar.auth.controller.admin.authRole.vo.AuthRoleResponseVO;
import com.stellar.auth.convert.AuthPermissionConvert;
import com.stellar.auth.convert.AuthRoleConvert;
import com.stellar.auth.domain.authRole.AuthRoleDomainService;

import com.stellar.web.core.bean.PageResult;
import com.stellar.web.core.enums.IsDeletedFlagEnum;
import com.stellar.web.core.enums.IsEnabledFlagENEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.stellar.core.util.ServiceExceptionUtil.exception;

/**
 * 角色表领域服务实现
 *
 * @author Jqchan
 * @version 1.0
 * @date 2025-05-16 18:07:02
 */
@Service
public class AuthRoleDomainServiceImpl implements AuthRoleDomainService {

    @Resource
    private AuthRoleService authRoleService;

    @Resource
    private AuthUserRoleService authUserRoleService;

    @Resource
    private AuthRolePermissionService authRolePermissionService;

    @Resource
    private AuthPermissionService authPermissionService;


    @Override
    public PageResult<AuthRoleResponseVO> page(AuthRoleRequestPageVO requestPageVO) {
        PageResult<AuthRoleResponseVO> pageResult = new PageResult<>();
        AuthRole queryEntity = AuthRoleConvert.INSTANCE.convert(requestPageVO);
        queryEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());

        List<AuthRole> entities = authRoleService.page(queryEntity,
                requestPageVO.getStart(), requestPageVO.getPageSize());

        if (entities.isEmpty()) {
            return pageResult;
        }

        Long count = authRoleService.count(queryEntity);
        List<AuthRoleResponseVO> vos = AuthRoleConvert.INSTANCE.convertEntityToRespList(entities);

        pageResult.setResult(vos);
        pageResult.setTotal(count.intValue());
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(AuthRoleRequestVO requestVO) {
        AuthRole entity = AuthRoleConvert.INSTANCE.convert(requestVO);
        int updateCount = authRoleService.update(entity);
        if (updateCount != 0) {
            // 删除原始关联
            authRolePermissionService.deleteByRoleId(requestVO.getId());
            // 批量关联角色权限
            if (CollectionUtil.isNotEmpty(requestVO.getPermissionIds())) {
                List<AuthRolePermission> authRolePermissions = requestVO.getPermissionIds().stream().map(permissionId -> {
                    AuthRolePermission authRolePermission = new AuthRolePermission();
                    authRolePermission.setRoleId(entity.getId());
                    authRolePermission.setPermissionId(permissionId);
                    authRolePermission.setCreatedTime(new Date());
                    authRolePermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
                    return authRolePermission;
                }).collect(Collectors.toList());
                authRolePermissionService.insertBatch(authRolePermissions);
            }
        }
        return updateCount != 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(Long id) {
        AuthRole entity = new AuthRole();
        entity.setId(id);
        entity.setIsDeleted(IsDeletedFlagEnum.DELETED.getVal());
        int updateCount = authRoleService.update(entity);
        if (updateCount != 0) {
            // 删除角色权限关联
            authRolePermissionService.deleteByRoleId(id);
        }
        return updateCount != 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insert(AuthRoleRequestVO requestVO) {
        AuthRole entity = AuthRoleConvert.INSTANCE.convert(requestVO);
        int insertCount = authRoleService.insert(entity);
        if (insertCount != 0) {
            // 批量关联角色权限
            if (CollectionUtil.isNotEmpty(requestVO.getPermissionIds())) {
                List<AuthRolePermission> authRolePermissions = requestVO.getPermissionIds().stream().map(permissionId -> {
                    AuthRolePermission authRolePermission = new AuthRolePermission();
                    authRolePermission.setRoleId(entity.getId());
                    authRolePermission.setPermissionId(permissionId);
                    authRolePermission.setCreatedTime(new Date());
                    authRolePermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
                    return authRolePermission;
                }).collect(Collectors.toList());
                authRolePermissionService.insertBatch(authRolePermissions);
            }
        }
        return insertCount != 0;
    }

    @Override
    public AuthRoleResponseVO get(Long id) {
        AuthRole entity = authRoleService.queryById(id);
        AuthRoleResponseVO roleResponseVO = AuthRoleConvert.INSTANCE.convert(entity);
        if (ObjectUtil.isNotNull(roleResponseVO)) {
            AuthRolePermission authRolePermission = new AuthRolePermission();
            authRolePermission.setRoleId(id);
            authRolePermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
            List<AuthRolePermission> authRolePermissions = authRolePermissionService.queryAllByCondition(authRolePermission);
            if (ObjectUtil.isNotNull(authRolePermissions)) {
                List<Long> permissionIds = authRolePermissions.stream().map(AuthRolePermission::getPermissionId).collect(Collectors.toList());
                if (!permissionIds.isEmpty()) {
                    List<AuthPermission> authPermissions = authPermissionService.batchQueryByIds(permissionIds);
                    List<AuthPermissionResponseVO> authPermissionResponseVOS = AuthPermissionConvert.INSTANCE.convertEntityToRespList(authPermissions);
                    roleResponseVO.setAuthPermissionResponseVOS(authPermissionResponseVOS);
                }
            }
        }
        return roleResponseVO;
    }

    @Override
    public List<AuthRoleResponseVO> getRoleByUserId(Long userId) {
        List<AuthUserRole> authUserRoles = authUserRoleService.queryByUserId(userId);
        if (CollectionUtil.isNotEmpty(authUserRoles)) {
            List<Long> roleIds = authUserRoles.stream().map(AuthUserRole::getRoleId).collect(Collectors.toList());
            List<AuthRole> authRoles = authRoleService.queryByIds(roleIds);
            return AuthRoleConvert.INSTANCE.convertEntityToRespList(authRoles);
        }
        throw exception(ErrorCodeConstants.AUTH_ROLE_IDENTITY_ERROR);
    }

    @Override
    public List<AuthRoleResponseVO> list() {
        AuthRole queryEntity = new AuthRole();
        queryEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
        queryEntity.setRoleStatus(IsEnabledFlagENEnum.ENABLED.getVal());
        List<AuthRole> entities = authRoleService.queryAllByCondition(queryEntity);
        return AuthRoleConvert.INSTANCE.convertEntityToRespList(entities);
    }
}
